{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f36d938c",
   "metadata": {},
   "source": [
    "# LLM Caching integrations\n",
    "\n",
    "This notebook covers how to cache results of individual LLM calls using different caches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "10ad9224",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.globals import set_llm_cache\n",
    "from langchain.llms import OpenAI\n",
    "\n",
    "# To make the caching really obvious, lets use a slower model.\n",
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", n=2, best_of=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b50f0598",
   "metadata": {
    "tags": []
   },
   "source": [
    "## `In Memory` Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "426ff912",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.cache import InMemoryCache\n",
    "\n",
    "set_llm_cache(InMemoryCache())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "64005d1f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 52.2 ms, sys: 15.2 ms, total: 67.4 ms\n",
      "Wall time: 1.19 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy couldn't the bicycle stand up by itself? Because it was...two tired!\""
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c8a1cb2b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 191 µs, sys: 11 µs, total: 202 µs\n",
      "Wall time: 205 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy couldn't the bicycle stand up by itself? Because it was...two tired!\""
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bf59c12",
   "metadata": {
    "tags": []
   },
   "source": [
    "## `SQLite` Cache"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aefd9d2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm .langchain.db"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5f036236",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can do the same thing with a SQLite cache\n",
    "from langchain.cache import SQLiteCache\n",
    "\n",
    "set_llm_cache(SQLiteCache(database_path=\".langchain.db\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fa18e3af",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 33.2 ms, sys: 18.1 ms, total: 51.2 ms\n",
      "Wall time: 667 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5bf2f6fd",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.86 ms, sys: 1.97 ms, total: 6.83 ms\n",
      "Wall time: 5.79 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e71273ab",
   "metadata": {},
   "source": [
    "## `Upstash Redis` Cache"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f10dabef",
   "metadata": {},
   "source": [
    "### Standard Cache\n",
    "Use [Upstash Redis](https://upstash.com) to cache prompts and responses with a serverless HTTP API."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f3920f25",
   "metadata": {},
   "outputs": [],
   "source": [
    "import langchain\n",
    "from langchain.cache import UpstashRedisCache\n",
    "from upstash_redis import Redis\n",
    "\n",
    "URL = \"<UPSTASH_REDIS_REST_URL>\"\n",
    "TOKEN = \"<UPSTASH_REDIS_REST_TOKEN>\"\n",
    "\n",
    "langchain.llm_cache = UpstashRedisCache(redis_=Redis(url=URL, token=TOKEN))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "3bf7d959",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 7.56 ms, sys: 2.98 ms, total: 10.5 ms\n",
      "Wall time: 1.14 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "00fc3a34",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2.78 ms, sys: 1.95 ms, total: 4.73 ms\n",
      "Wall time: 82.9 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "278ad7ae",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `Redis` Cache"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5c9a4d5",
   "metadata": {},
   "source": [
    "### Standard Cache\n",
    "Use [Redis](/docs/ecosystem/integrations/redis) to cache prompts and responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "39f6eb0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can do the same thing with a Redis cache\n",
    "# (make sure your local Redis instance is running first before running this example)\n",
    "from langchain.cache import RedisCache\n",
    "from redis import Redis\n",
    "\n",
    "set_llm_cache(RedisCache(redis_=Redis()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28920749",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 6.88 ms, sys: 8.75 ms, total: 15.6 ms\n",
      "Wall time: 1.04 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "94bf9415",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.59 ms, sys: 610 µs, total: 2.2 ms\n",
      "Wall time: 5.58 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82be23f6",
   "metadata": {},
   "source": [
    "### Semantic Cache\n",
    "Use [Redis](/docs/ecosystem/integrations/redis) to cache prompts and responses and evaluate hits based on semantic similarity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "64df3099",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.cache import RedisSemanticCache\n",
    "from langchain.embeddings import OpenAIEmbeddings\n",
    "\n",
    "set_llm_cache(\n",
    "    RedisSemanticCache(redis_url=\"redis://localhost:6379\", embedding=OpenAIEmbeddings())\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8e91d3ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 351 ms, sys: 156 ms, total: 507 ms\n",
      "Wall time: 3.37 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "df856948",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 6.25 ms, sys: 2.72 ms, total: 8.97 ms\n",
      "Wall time: 262 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"\\n\\nWhy don't scientists trust atoms?\\nBecause they make up everything.\""
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time, while not a direct hit, the question is semantically similar to the original question,\n",
    "# so it uses the cached result!\n",
    "llm(\"Tell me one joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "684eab55",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `GPTCache`\n",
    "\n",
    "We can use [GPTCache](https://github.com/zilliztech/GPTCache) for exact match caching OR to cache results based on semantic similarity\n",
    "\n",
    "Let's first start with an example of exact match"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "14a82124",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "\n",
    "from gptcache import Cache\n",
    "from gptcache.manager.factory import manager_factory\n",
    "from gptcache.processor.pre import get_prompt\n",
    "from langchain.cache import GPTCache\n",
    "\n",
    "\n",
    "def get_hashed_name(name):\n",
    "    return hashlib.sha256(name.encode()).hexdigest()\n",
    "\n",
    "\n",
    "def init_gptcache(cache_obj: Cache, llm: str):\n",
    "    hashed_llm = get_hashed_name(llm)\n",
    "    cache_obj.init(\n",
    "        pre_embedding_func=get_prompt,\n",
    "        data_manager=manager_factory(manager=\"map\", data_dir=f\"map_cache_{hashed_llm}\"),\n",
    "    )\n",
    "\n",
    "\n",
    "set_llm_cache(GPTCache(init_gptcache))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e4ecfd1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 21.5 ms, sys: 21.3 ms, total: 42.8 ms\n",
      "Wall time: 6.2 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c98bbe3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 571 µs, sys: 43 µs, total: 614 µs\n",
      "Wall time: 635 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "502b6076",
   "metadata": {},
   "source": [
    "Let's now show an example of similarity caching"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b3c663bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "\n",
    "from gptcache import Cache\n",
    "from gptcache.adapter.api import init_similar_cache\n",
    "from langchain.cache import GPTCache\n",
    "\n",
    "\n",
    "def get_hashed_name(name):\n",
    "    return hashlib.sha256(name.encode()).hexdigest()\n",
    "\n",
    "\n",
    "def init_gptcache(cache_obj: Cache, llm: str):\n",
    "    hashed_llm = get_hashed_name(llm)\n",
    "    init_similar_cache(cache_obj=cache_obj, data_dir=f\"similar_cache_{hashed_llm}\")\n",
    "\n",
    "\n",
    "set_llm_cache(GPTCache(init_gptcache))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8c273ced",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.42 s, sys: 279 ms, total: 1.7 s\n",
      "Wall time: 8.44 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "93e21a5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 866 ms, sys: 20 ms, total: 886 ms\n",
      "Wall time: 226 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# This is an exact match, so it finds it in the cache\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c4bb024b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 853 ms, sys: 14.8 ms, total: 868 ms\n",
      "Wall time: 224 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side.'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# This is not an exact match, but semantically within distance so it hits!\n",
    "llm(\"Tell me joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "726fe754",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `Momento` Cache\n",
    "Use [Momento](/docs/ecosystem/integrations/momento) to cache prompts and responses.\n",
    "\n",
    "Requires momento to use, uncomment below to install:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8949f29",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install momento"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56ea6a08",
   "metadata": {},
   "source": [
    "You'll need to get a Momento auth token to use this class. This can either be passed in to a momento.CacheClient if you'd like to instantiate that directly, as a named parameter `auth_token` to `MomentoChatMessageHistory.from_client_params`, or can just be set as an environment variable `MOMENTO_AUTH_TOKEN`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2005f03a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import timedelta\n",
    "\n",
    "from langchain.cache import MomentoCache\n",
    "\n",
    "cache_name = \"langchain\"\n",
    "ttl = timedelta(days=1)\n",
    "set_llm_cache(MomentoCache.from_client_params(cache_name, ttl))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c6a6c238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 40.7 ms, sys: 16.5 ms, total: 57.2 ms\n",
      "Wall time: 1.73 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The first time, it is not yet in cache, so it should take longer\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b8f78f9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 3.16 ms, sys: 2.98 ms, total: 6.14 ms\n",
      "Wall time: 57.9 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# The second time it is, so it goes faster\n",
    "# When run in the same region as the cache, latencies are single digit ms\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "934943dc",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## `SQLAlchemy` Cache\n",
    "\n",
    "You can use `SQLAlchemyCache` to cache with any SQL database supported by `SQLAlchemy`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acccff40",
   "metadata": {},
   "outputs": [],
   "source": [
    "# from langchain.cache import SQLAlchemyCache\n",
    "# from sqlalchemy import create_engine\n",
    "\n",
    "# engine = create_engine(\"postgresql://postgres:postgres@localhost:5432/postgres\")\n",
    "# set_llm_cache(SQLAlchemyCache(engine))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0959d640",
   "metadata": {},
   "source": [
    "### Custom SQLAlchemy Schemas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac967b39",
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can define your own declarative SQLAlchemyCache child class to customize the schema used for caching. For example, to support high-speed fulltext prompt indexing with Postgres, use:\n",
    "\n",
    "from langchain.cache import SQLAlchemyCache\n",
    "from sqlalchemy import Column, Computed, Index, Integer, Sequence, String, create_engine\n",
    "from sqlalchemy.ext.declarative import declarative_base\n",
    "from sqlalchemy_utils import TSVectorType\n",
    "\n",
    "Base = declarative_base()\n",
    "\n",
    "\n",
    "class FulltextLLMCache(Base):  # type: ignore\n",
    "    \"\"\"Postgres table for fulltext-indexed LLM Cache\"\"\"\n",
    "\n",
    "    __tablename__ = \"llm_cache_fulltext\"\n",
    "    id = Column(Integer, Sequence(\"cache_id\"), primary_key=True)\n",
    "    prompt = Column(String, nullable=False)\n",
    "    llm = Column(String, nullable=False)\n",
    "    idx = Column(Integer)\n",
    "    response = Column(String)\n",
    "    prompt_tsv = Column(\n",
    "        TSVectorType(),\n",
    "        Computed(\"to_tsvector('english', llm || ' ' || prompt)\", persisted=True),\n",
    "    )\n",
    "    __table_args__ = (\n",
    "        Index(\"idx_fulltext_prompt_tsv\", prompt_tsv, postgresql_using=\"gin\"),\n",
    "    )\n",
    "\n",
    "\n",
    "engine = create_engine(\"postgresql://postgres:postgres@localhost:5432/postgres\")\n",
    "set_llm_cache(SQLAlchemyCache(engine, FulltextLLMCache))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eeba7d60",
   "metadata": {},
   "source": [
    "## `Cassandra` caches\n",
    "\n",
    "You can use Cassandra / Astra DB through CQL for caching LLM responses, choosing from the exact-match `CassandraCache` or the (vector-similarity-based) `CassandraSemanticCache`.\n",
    "\n",
    "Let's see both in action in the following cells."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4a6725d",
   "metadata": {},
   "source": [
    "#### Connect to the DB\n",
    "\n",
    "First you need to establish a `Session` to the DB and to specify a _keyspace_ for the cache table(s). The following gets you connected to Astra DB through CQL (see e.g. [here](https://cassio.org/start_here/#vector-database) for more backends and connection options)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cc53ce1b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Keyspace name? my_keyspace\n",
      "\n",
      "Astra DB Token (\"AstraCS:...\") ········\n",
      "Full path to your Secure Connect Bundle? /path/to/secure-connect-databasename.zip\n"
     ]
    }
   ],
   "source": [
    "import getpass\n",
    "\n",
    "keyspace = input(\"\\nKeyspace name? \")\n",
    "ASTRA_DB_APPLICATION_TOKEN = getpass.getpass('\\nAstra DB Token (\"AstraCS:...\") ')\n",
    "ASTRA_DB_SECURE_BUNDLE_PATH = input(\"Full path to your Secure Connect Bundle? \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4617f485",
   "metadata": {},
   "outputs": [],
   "source": [
    "from cassandra.auth import PlainTextAuthProvider\n",
    "from cassandra.cluster import Cluster\n",
    "\n",
    "cluster = Cluster(\n",
    "    cloud={\n",
    "        \"secure_connect_bundle\": ASTRA_DB_SECURE_BUNDLE_PATH,\n",
    "    },\n",
    "    auth_provider=PlainTextAuthProvider(\"token\", ASTRA_DB_APPLICATION_TOKEN),\n",
    ")\n",
    "session = cluster.connect()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8665664a",
   "metadata": {},
   "source": [
    "### Exact cache\n",
    "\n",
    "This will avoid invoking the LLM when the supplied prompt is _exactly_ the same as one encountered already:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "00a5e66f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.cache import CassandraCache\n",
    "from langchain.globals import set_llm_cache\n",
    "\n",
    "set_llm_cache(CassandraCache(session=session, keyspace=keyspace))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "956a5145",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon always shows the same side because it is tidally locked to Earth.\n",
      "CPU times: user 41.7 ms, sys: 153 µs, total: 41.8 ms\n",
      "Wall time: 1.96 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Why is the Moon always showing the same side?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "158f0151",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon always shows the same side because it is tidally locked to Earth.\n",
      "CPU times: user 4.09 ms, sys: 0 ns, total: 4.09 ms\n",
      "Wall time: 119 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Why is the Moon always showing the same side?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fc4d017",
   "metadata": {},
   "source": [
    "### Semantic cache\n",
    "\n",
    "This cache will do a semantic similarity search and return a hit if it finds a cached entry that is similar enough, For this, you need to provide an `Embeddings` instance of your choice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "b9ad3f54",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings import OpenAIEmbeddings\n",
    "\n",
    "embedding = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "4623f95e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.cache import CassandraSemanticCache\n",
    "\n",
    "set_llm_cache(\n",
    "    CassandraSemanticCache(\n",
    "        session=session,\n",
    "        keyspace=keyspace,\n",
    "        embedding=embedding,\n",
    "        table_name=\"cass_sem_cache\",\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "1a8e577b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon always shows the same side because it is tidally locked with Earth. This means that the same side of the Moon always faces Earth.\n",
      "CPU times: user 21.3 ms, sys: 177 µs, total: 21.4 ms\n",
      "Wall time: 3.09 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Why is the Moon always showing the same side?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "f7abddfd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "The Moon always shows the same side because it is tidally locked with Earth. This means that the same side of the Moon always faces Earth.\n",
      "CPU times: user 10.9 ms, sys: 17 µs, total: 10.9 ms\n",
      "Wall time: 461 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"How come we always see one face of the moon?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8712f8fc-bb89-4164-beb9-c672778bbd91",
   "metadata": {},
   "source": [
    "## `Astra DB` Caches"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "173041d9-e4af-4f68-8461-d302bfc7e1bd",
   "metadata": {},
   "source": [
    "You can easily use [Astra DB](https://docs.datastax.com/en/astra/home/astra.html) as an LLM cache, with either the \"exact\" or the \"semantic-based\" cache.\n",
    "\n",
    "Make sure you have a running database (it must be a Vector-enabled database to use the Semantic cache) and get the required credentials on your Astra dashboard:\n",
    "\n",
    "- the API Endpoint looks like `https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com`\n",
    "- the Token looks like `AstraCS:6gBhNmsk135....`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "feb510b6-99a3-4228-8e11-563051f8178e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ASTRA_DB_API_ENDPOINT =  https://01234567-89ab-cdef-0123-456789abcdef-us-east1.apps.astra.datastax.com\n",
      "ASTRA_DB_APPLICATION_TOKEN =  ········\n"
     ]
    }
   ],
   "source": [
    "import getpass\n",
    "\n",
    "ASTRA_DB_API_ENDPOINT = input(\"ASTRA_DB_API_ENDPOINT = \")\n",
    "ASTRA_DB_APPLICATION_TOKEN = getpass.getpass(\"ASTRA_DB_APPLICATION_TOKEN = \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee6d587f-4b7c-43f4-9e90-5129c842a143",
   "metadata": {},
   "source": [
    "### Astra DB exact LLM cache\n",
    "\n",
    "This will avoid invoking the LLM when the supplied prompt is _exactly_ the same as one encountered already:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ad63c146-ee41-4896-90ee-29fcc39f0ed5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.cache import AstraDBCache\n",
    "from langchain.globals import set_llm_cache\n",
    "\n",
    "set_llm_cache(\n",
    "    AstraDBCache(\n",
    "        api_endpoint=ASTRA_DB_API_ENDPOINT,\n",
    "        token=ASTRA_DB_APPLICATION_TOKEN,\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "83e0fb02-e8eb-4483-9eb1-55b5e14c4487",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question as it depends on the interpretation of the terms \"true fakery\" and \"fake truth\". However, one possible interpretation is that a true fakery is a counterfeit or imitation that is intended to deceive, whereas a fake truth is a false statement that is presented as if it were true.\n",
      "CPU times: user 70.8 ms, sys: 4.13 ms, total: 74.9 ms\n",
      "Wall time: 2.06 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Is a true fakery the same as a fake truth?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "4d20d498-fe28-4e26-8531-2b31c52ee687",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question as it depends on the interpretation of the terms \"true fakery\" and \"fake truth\". However, one possible interpretation is that a true fakery is a counterfeit or imitation that is intended to deceive, whereas a fake truth is a false statement that is presented as if it were true.\n",
      "CPU times: user 15.1 ms, sys: 3.7 ms, total: 18.8 ms\n",
      "Wall time: 531 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Is a true fakery the same as a fake truth?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "524b94fa-6162-4880-884d-d008749d14e2",
   "metadata": {},
   "source": [
    "### Astra DB Semantic cache\n",
    "\n",
    "This cache will do a semantic similarity search and return a hit if it finds a cached entry that is similar enough, For this, you need to provide an `Embeddings` instance of your choice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "dc329c55-1cc4-4b74-94f9-61f8990fb214",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings import OpenAIEmbeddings\n",
    "\n",
    "embedding = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "83952a90-ab14-4e59-87c0-d2bdc1d43e43",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.cache import AstraDBSemanticCache\n",
    "\n",
    "set_llm_cache(\n",
    "    AstraDBSemanticCache(\n",
    "        api_endpoint=ASTRA_DB_API_ENDPOINT,\n",
    "        token=ASTRA_DB_APPLICATION_TOKEN,\n",
    "        embedding=embedding,\n",
    "        collection_name=\"demo_semantic_cache\",\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d74b249a-94d5-42d0-af74-f7565a994dea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question since it presupposes a great deal about the nature of truth itself, which is a matter of considerable philosophical debate. It is possible, however, to construct scenarios in which something could be considered true despite being false, such as if someone sincerely believes something to be true even though it is not.\n",
      "CPU times: user 65.6 ms, sys: 15.3 ms, total: 80.9 ms\n",
      "Wall time: 2.72 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Are there truths that are false?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "11973d73-d2f4-46bd-b229-1c589df9b788",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "There is no definitive answer to this question since it presupposes a great deal about the nature of truth itself, which is a matter of considerable philosophical debate. It is possible, however, to construct scenarios in which something could be considered true despite being false, such as if someone sincerely believes something to be true even though it is not.\n",
      "CPU times: user 29.3 ms, sys: 6.21 ms, total: 35.5 ms\n",
      "Wall time: 1.03 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "print(llm(\"Is is possible that something false can be also true?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c69d84d",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## Optional Caching\n",
    "You can also turn off caching for specific LLMs should you choose. In the example below, even though global caching is enabled, we turn it off for a specific LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "6af46e2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", n=2, best_of=2, cache=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "26c4fd8f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 5.8 ms, sys: 2.71 ms, total: 8.51 ms\n",
      "Wall time: 745 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nWhy did the chicken cross the road?\\n\\nTo get to the other side!'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "46846b20",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.91 ms, sys: 2.64 ms, total: 7.55 ms\n",
      "Wall time: 623 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nTwo guys stole a calendar. They got six months each.'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "llm(\"Tell me a joke\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5da41b77",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "## Optional Caching in Chains\n",
    "You can also turn off caching for particular nodes in chains. Note that because of certain interfaces, its often easier to construct the chain first, and then edit the LLM afterwards.\n",
    "\n",
    "As an example, we will load a summarizer map-reduce chain. We will cache results for the map-step, but then not freeze it for the combine step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9afa3f7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\")\n",
    "no_cache_llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", cache=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "98a78e8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "\n",
    "text_splitter = CharacterTextSplitter()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "2bfb099b",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"../../modules/state_of_the_union.txt\") as f:\n",
    "    state_of_the_union = f.read()\n",
    "texts = text_splitter.split_text(state_of_the_union)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f78b7f51",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.docstore.document import Document\n",
    "\n",
    "docs = [Document(page_content=t) for t in texts[:3]]\n",
    "from langchain.chains.summarize import load_summarize_chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "a2a30822",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = load_summarize_chain(llm, chain_type=\"map_reduce\", reduce_llm=no_cache_llm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a545b743",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 452 ms, sys: 60.3 ms, total: 512 ms\n",
      "Wall time: 5.09 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure. In response to Russian aggression in Ukraine, the United States is joining with European allies to impose sanctions and isolate Russia. American forces are being mobilized to protect NATO countries in the event that Putin decides to keep moving west. The Ukrainians are bravely fighting back, but the next few weeks will be hard for them. Putin will pay a high price for his actions in the long run. Americans should not be alarmed, as the United States is taking action to protect its interests and allies.'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "chain.run(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ed85e9d",
   "metadata": {},
   "source": [
    "When we run it again, we see that it runs substantially faster but the final answer is different. This is due to caching at the map steps, but not at the reduce step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "39cbb282",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 11.5 ms, sys: 4.33 ms, total: 15.8 ms\n",
      "Wall time: 1.04 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure.'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "chain.run(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9df0dab8",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm .langchain.db sqlite.db"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
